package com.tanhua.app.service;

import com.tanhua.api.PeachSoundsApi;
import com.tanhua.api.UserInfoApi;
import com.tanhua.api.UserLikeApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.model.pojo.Sounds;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.SoundsVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

@Service
public class PeachBlossomService {


    @DubboReference
    private PeachSoundsApi peachSoundsApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;


    @DubboReference
    private UserInfoApi userInfoApi;




    /*生成声音表数据*/
    public void saveUserSounds(MultipartFile soundFile) throws IOException {
        //查询发送语音剩余次数
        Long userId = UserHolder.getUserId();
        String times = redisTemplate.opsForValue().get(Constants.PEACH_SEND_KEY + userId);

        if (times == null) {
            times = "0";
            redisTemplate.opsForValue().set(Constants.PEACH_SEND_KEY + userId, times, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        }
        if (Integer.valueOf(times) >= 10) {
            throw new BusinessException(ErrorResult.setVoiceTimeError());
        }

        /*将redis数据更新成+1*/
        times = Integer.valueOf(times) + 1 + "";
        redisTemplate.opsForValue().set(Constants.PEACH_SEND_KEY + userId, times, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);

        /*判断语音是否为空*/
        if (soundFile == null || soundFile.isEmpty()) {
            throw new BusinessException(ErrorResult.saveVoiceError());
        }

        /*将语音上传至oss服务器*/
        String soundUrl = ossTemplate.uploadOss(soundFile.getInputStream(), soundFile.getOriginalFilename());

        Sounds sounds = new Sounds();
        sounds.setSoundUrl(soundUrl);
        sounds.setUserId(userId);
        peachSoundsApi.saveSounds(sounds);
    }


    /**
     * 判断当前时间距离第二天凌晨的秒数
     *
     * @return 返回值单位为[s:秒]
     */
    public Long getSecondsNextEarlyMorning() {
        LocalDate localDate = LocalDate.now();
        // 当前日期+1
        localDate = localDate.plusDays(1);
        LocalDateTime dateTime = LocalDateTime.of(localDate.getYear(), localDate.getMonth(), localDate.getDayOfMonth(), 0, 0, 0);

        return (-System.currentTimeMillis() + dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) / 1000;
    }


    /*获取声音数据并将数据状态更新为1*/
    public SoundsVo getOneSounds() {

        /*一天十条,redis有效期到第二天凌晨0:00截止*/


        /*查寻redis获取剩余次数*/
        Long userId = UserHolder.getUserId();
        String times = redisTemplate.opsForValue().get(Constants.PEACH_BLOSSOM_KEY + userId);

        if (times == null) {
            times = "0";
            redisTemplate.opsForValue().set(Constants.PEACH_BLOSSOM_KEY + userId, times, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        }
        if (Integer.valueOf(times) >= 10) {
            throw new BusinessException(ErrorResult.getVoiceTimeError());
        }

        /*从数据库(按顺序)获取一条is_used状态为0的数据并且更新状态为1*/


        Sounds sounds = peachSoundsApi.getOneSounds(UserHolder.getUserId());

        if (sounds == null) {
            throw new BusinessException(ErrorResult.getVoiceError());
        }

        UserInfo userInfo = userInfoApi.findById(sounds.getUserId());


        /*将redis数据更新成+1*/
        times = Integer.valueOf(times) + 1 + "";
        redisTemplate.opsForValue().set(Constants.PEACH_BLOSSOM_KEY + userId, times, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        SoundsVo soundsVo = new SoundsVo();
        if (userInfo != null) {
            soundsVo.setId(sounds.getUserId().intValue());
            soundsVo.setSoundUrl(sounds.getSoundUrl());
            soundsVo.setNickname(userInfo.getNickname());
            soundsVo.setAge(userInfo.getAge());
            soundsVo.setGender(userInfo.getGender());
            soundsVo.setRemainingTimes(10 - Integer.valueOf(times));
            soundsVo.setAvatar(userInfo.getAvatar());
        }
        return soundsVo;
    }

}
